﻿using Newtonsoft.Json;
using System.Net;
using System.Text;

namespace Util
{
    public class HttpHelper
    {
        //contentType application/json or application/xml
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string Url)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    //get
                    var url = new Uri(Url);
                    // response
                    var response = httpClient.GetAsync(url).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <param name="contentType"></param>
        /// <param name="isOK"></param>
        /// <returns></returns>
        public static object HttpPost(string Url, string postDataStr, out bool isOK, string contentType = "application/json;charset=UTF-8")
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.Timeout = 5000;
                request.ContentType = contentType;
                byte[] byteData = Encoding.UTF8.GetBytes(postDataStr);
                int length = byteData.Length;
                request.ContentLength = length;
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(byteData, 0, length);
                    writer.Close();
                }
                string jsonStrings = string.Empty;
                using (HttpWebResponse responses = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream streams = responses.GetResponseStream())
                    {
                        using (StreamReader readers = new StreamReader(streams, System.Text.Encoding.UTF8))
                        {
                            jsonStrings = readers.ReadToEnd();
                            responses.Close();
                            streams.Close();
                            readers.Close();
                        }
                    }
                }
                //这里是返回的数据
                isOK = true;
                return JsonConvert.DeserializeObject(jsonStrings);
            }
            catch (Exception ex)
            {
                isOK = false;
                return null;
            }
        }
    }
}
